package com.jm.product.provider;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jm.product.entity.GoodsType;
import com.jm.product.entity.dto.GoodsParam;
import com.jm.product.entity.dto.ParamGroup;
import com.jm.product.provider.core.BaseService;
import com.jm.product.service.GoodsTypeService;
//import com.jm.product.dao.GoodsTypeDao;

/**
 * 商品类型Service
 * @author sunshine
 * @version 2017-06-30
 */

@Service
@Transactional(readOnly = true)
public class GoodsTypeServiceImpl extends BaseService<GoodsType,Integer> implements GoodsTypeService {

    public GoodsTypeServiceImpl(){
        //default constructor
    	super();
    }

	public GoodsType get(Integer id) {
		return dao.get(id);
	}

	@Override
	public List<ParamGroup> toParamList(String[] paramnums, String[] groupnames, String[] paramnames,
			String[] paramvalues) {
		 List<ParamGroup> list = new ArrayList<ParamGroup>();
		    if (groupnames != null) {
		      for (int i = 0; i < groupnames.length; i++) {
		        ParamGroup paramGroup = new ParamGroup();
		        paramGroup.setName(groupnames[i]);
		        List<GoodsParam> paramList = getParamList(paramnums, paramnames, paramvalues, i);
		        paramGroup.setParamList(paramList);
		        list.add(paramGroup);
		      }
		    }
		    return list;
	}
	
	 private List<GoodsParam> getParamList(String[] paramnums, String[] paramnames, String[] paramvalues, int groupindex) {
		    int[] pos = countPos(groupindex, paramnums);
		    List<GoodsParam> list = new ArrayList<GoodsParam>();
		    for (int i = pos[0]; i < pos[1]; i++) {
		      GoodsParam goodsParam = new GoodsParam();
		      goodsParam.setName(paramnames[i]);
		      if (paramvalues != null) {
		        String value = paramvalues[i];
		        goodsParam.setValue(value);
		      }
		      list.add(goodsParam);
		    }
		    return list;
		  }
		  
		  private int[] countPos(int groupindex, String[] paramnums) {
		    int index = 0;
		    int start = 0;
		    int end = 0;
		    int[] r = new int[2];
		    for (int i = 0; i <= groupindex; i++) {
		      int p_num = Integer.valueOf(paramnums[i]).intValue();
		      index += p_num;
		      if (i == groupindex - 1) {
		        start = index;
		      }
		      if (i == groupindex) {
		        end = index;
		      }
		    }
		    r[0] = start;
		    r[1] = end;
		    
		    return r;
		  }
}
